<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input class="filter-input-container" v-model="listQuery.keyWord" clearable style="width: 200px;"
        placeholder="请输入用户名" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" icon="el-icon-refresh-right" @click="handleReset">重置</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table stripe v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit
      highlight-current-row>
      <el-table-column align="center" width="100px" label="用户ID" prop="userId" sortable />
      <el-table-column align="center" show-overflow-tooltip label="用户名" prop="userName" />
      <el-table-column align="center" label="性别" prop="genderStr" />
      <el-table-column align="center" label="真实姓名" prop="fullName" />
      <el-table-column align="center" label="用户头像" width="80">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.imgUrl" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号码" prop="phone">
        <template slot-scope="scope">
          {{ scope.row.phone || "-" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="生日" prop="birthday">
        <template slot-scope="scope">
          {{ scope.row.birthday || "-" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户等级" prop="vipLevel">
        <template slot-scope="scope">
          <el-tag>{{ levelDic[scope.row.vipLevel] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="用户类型" prop="userTypeStr">
      </el-table-column>

      <el-table-column align="center" label="最近登录时间" prop="lastLoginTime">
        <template slot-scope="scope">
          {{ scope.row.lastLoginTime || "-" }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="用户状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{
            getLabel(userStatus, scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
      @pagination="getList" />
    <!-- 用户详情对话框 -->
    <el-dialog @close="handleClose" width="40%" :visible.sync="userDialogVisible" title="用户信息">
      <el-form ref="userDetail" :model="userDetail" status-icon label-position="left" label-width="100px"
        style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userDetail.userName" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="fullName">
          <el-input clearable v-model="userDetail.fullName" />
        </el-form-item>
        <el-form-item label="用户手机" prop="phone">
          <el-input clearable v-model="userDetail.phone" />
        </el-form-item>
        <el-form-item label="用户性别" prop="genderStr">
          <el-select clearable v-model="userDetail.gender" placeholder="请选择"><el-option v-for="(item, index) in genderDic"
              :key="index" :label="item" :value="index" /></el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable v-model="userDetail.birthday" type="date" placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserUpdate">确定</el-button>
      </div>
    </el-dialog>
    <el-drawer size="30%" title="用户信息" :visible.sync="userDrawerVisible" :with-header="false">
      <div class="user-detail-box">
        <el-descriptions title="用户信息" size="medium" :column="2" border>
          <el-descriptions-item label="用户名">{{ userDetail.userName }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ userDetail.fullName || "-" }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userDetail.phone || "-" }}</el-descriptions-item>
          <el-descriptions-item label="生日">{{ userDetail.birthday || "-" }}</el-descriptions-item>
          <el-descriptions-item label="会员等级"><el-tag>{{ levelDic[userDetail.vipLevel]
          }}</el-tag></el-descriptions-item>
          <el-descriptions-item label="用户类型">
            <el-tag size="small">{{ userDetail.userTypeStr }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- <div>
        <el-button></el-button>
      </div> -->
    </el-drawer>
  </div>
</template>

<script>
import { fetchList, userDetail, updateUser, updateUserStatus, userAdd } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getLabel } from "@/utils/index.js"
import { userStatus } from "@/data/dict.js"

export default {
  name: 'User',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "danger",
        1: "success",
        2: "info",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      userStatus,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        userType: "2",
        currentPage: 1,
        pageSize: 20,
        keyWord: ''
      },
      downloadLoading: false,
      genderDic: ['男', '女'],
      levelDic: ['普通用户', 'VIP用户', '高级VIP用户'],
      statusDic: ['可用', '禁用', '注销'],
      userDialogVisible: false,
      userDrawerVisible: false,
      userDetail: {
      },
      dialogType: 'edit' //弹窗类型
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getLabel,
    getList() {
      this.listLoading = true
      if (this.listQuery.userId) {
        userDetail(this.listQuery.userId).then(response => {
          this.list = []
          if (response.data) {
            this.list.push(response.data)
            this.total = 1
            this.listLoading = false
          } else {
            this.list = []
            this.total = 0
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        fetchList(this.listQuery).then(response => {
          console.log('response', response)
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户名', '手机号码', '性别', '生日', '状态']
        const filterVal = ['username', 'mobile', 'gender', 'birthday', 'status']
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '用户信息')
        this.downloadLoading = false
      })
    },
    handleDetail(row) {
      this.userDetail = row
      this.userDrawerVisible = true
    },
    //用户状态修改
    handleModifyUserStatus(row, type) {
      // console.log('row---------------', row);
      let params = {
        userId: row.userId,
        status: type === "stop" ? "0" : "1"
      }
      updateUserStatus(params).then((res) => {
        if (res.code === 200) {
          this.$message.success("状态更新成功！")
          this.getList();
        } else {
          this.$message.error("数据更新失败，请联系管理员")
        }
      })

    },
    handleUserUpdate() {
      if (this.dialogType === 'edit') {
        updateUser(this.userDetail)
          .then((response) => {
            this.userDialogVisible = false
            this.$notify.success({
              title: '成功',
              message: '更新用户成功'
            })
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      } else {
        let params = { ...this.userDetail }
        params.userType = '1'
        userAdd(params).then(res => {
          if (res.code === 200) {
            console.log('res=================', res);
            this.userDetail = {}
            this.userDialogVisible = false;
            this.$message.success("添加成功！")
            this.getList();
          }
        })
      }

    },
    //重置
    handleReset() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        userType: "2",
        keyWord: ''
      }
      this.getList();
    },
    //编辑弹窗
    handleEdit(row) {
      this.userDialogVisible = true
      this.userDetail = JSON.parse(JSON.stringify(row))
    },
    //添加用户
    handleAdd() {
      this.dialogType = 'add'
      this.userDialogVisible = true;
    },
    handleClose() {
      this.userDialogVisible = false;
      this.userDetail = {}
      this.dialogType = 'edit'
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-item {
  margin-left: 20px;
  vertical-align: initial;

  &.add {
    float: right;
  }
}

.filter-input-container {
  margin-left: 0px
}

.user-detail-box {
  padding: 16px;
}

:deep(.el-drawer__header) {
  height: 20px;
  margin-bottom: 10px;
}
</style>
